﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace weiqijiance.信号处理模块
{
    //这个类用于控制两块信号板的接收处理与发送
    public class DACcontrol
    {

        ///////////////////////////////////
        public float[] fAIDataSU = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//采样值AI 信号不修正
        public float[] fAIData = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//修正后采样值AI 信号
        //public float[] fAIDataex = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//采样值AI 信号
        public float[] fAIDataZero = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//零点漂移值  用于调零使用

        public bool[] bDIData = new bool[16] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false };//采样值DI 信号
        public float[] fTIData = new float[4] { 0, 0, 0, 0 };//采样值TI 信号

        DACBase[] dacxh = new DACBase[2];// { new DACBase(), new DACBase() };
        //public mainform m_mainform;
        public bool bthread = false;
      //DACBase  dac1 = new DACBase();
      //DACBase dac2 = new DACBase();
        public DACcontrol()
        {
            dacxh[0] = new DACBase();
            dacxh[1] = new DACBase();
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="scomm">串口</param>
        /// <param name="iindex">第几块信号板</param>
        /// <param name="bnew">是否新信号板</param>
        public void opencomm(string scomm, int iindex, string version)
        {
            if (dacxh[iindex - 1].iopen==1)
            {
                return;
            }
            if (version.Contains("1.4"))
            {
                dacxh[iindex - 1] = new DACnew();
                dacxh[iindex - 1].openCOM(scomm);
                dacxh[iindex - 1].iopen = 2;
            }
            else if (version.Contains("1.0"))
            {
                dacxh[iindex - 1] = new DACold();
                dacxh[iindex - 1].openCOM(scomm);
                dacxh[iindex - 1].iopen = 2;
            }
            else if (version.Contains("2.0"))
            {
                dacxh[iindex - 1] = new DACnewV2();
                dacxh[iindex - 1].openCOM(scomm);
                dacxh[iindex - 1].iopen = 2;
            }
            else
            {
                dacxh[iindex - 1].iopen = 1;
                MessageBox.Show("请选择信号板版本");
            }
            dacxh[iindex - 1].sxhbmc = string.Format("{0}号板", iindex);
        }
        Thread t1;
        /// <summary>
        /// 开始线程取数
        /// </summary>
        public void start()
        {
            //如果线程已经开始，return,如果线程未开启，往下走打开线程
            if (bthread)
                return;
            bthread = true;
            t1 = new Thread(Thread1);
            t1.Start();
        }
        float[,] fAI;
        int icount = 0;
        
        public void Thread1()
        {
            int icountZS = 20;
            fAI = new float[10, icountZS];
            while (true)
            {
                getditi();
                for (int z = 0; z < dacxh.Length; z++)
                {
                    getxinhao(dacxh[z], z);
                }
                icount++;
                float[] fAIzs = new float[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                for (int i = 0; i < 10; i++)
                {
                    for (int j = 0; j < icount; j++)
                    {
                        fAIzs[i] += fAI[i, j];
                    }
                    fAIData[i] = fAIzs[i] / icount;
                }
                if (icount > icountZS - 1)
                {
                    icount--;
                    for (int j = 0; j < icountZS - 1; j++)
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            fAI[i, j] = fAI[i, j + 1];
                        }
                    }
                }
                Thread.Sleep(5);
            }
        }

        public void Thread2()
        {
        }
        public void getditi()
        {
            {
                for (int i = 0; i < 16; i++)
                {
                    bDIData[i] = dacxh[i / 8].bDIData[i % 8];
                }
            }
            {
                for (int i = 0; i < 4; i++)
                {
                    fTIData[i] = dacxh[i / 2].fTIData[i % 2];
                }
            }
        }
        public void getxinhao(DACBase dac, int iindex)
        {
            int ixs = iindex * 5;
            for (int i = 0; i < 5; i++)
            {
                fAI[i + ixs, icount] = dac.fAIDataex[i];
                fAIDataSU[i + ixs] = dac.fAIDataex[i];
            }
        }

        public void PutVol(double fOutPut)//模块电流输出
        {
            dacxh[0].PutVol(fOutPut);//涡流输出必须用第一块电路板
        }

        public void SetDOBit(short m_uChannel, short uData)//数字位输出
        {
            if (m_uChannel < 0)
                return;
            dacxh[m_uChannel / 8].SetDOBit((short)(m_uChannel%8), uData);
        }
        /////模拟信号调零
        public void tiaoling(int icount = 0)
        {
            
            float[] fzero1 = new float[50];
            float[] fzero2 = new float[50];
            float[] fzero3 = new float[50];
            float[] fzero4 = new float[50];
            float[] fzero5 = new float[50];
            float[] fzero6 = new float[50];
            float[] fzero7 = new float[50];
            float[] fzero8 = new float[50];
            float[] fzero9 = new float[50];
            float[] fzero10 = new float[50];

            float[,] fzeros = new float[10, 50];

            for (int i = 0; i < 50; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    fzeros[j, i] = fAIData[j];
                }
                System.Threading.Thread.Sleep(20);
            }
            for (int i = 0; i < 50; i++)
            {
                for (int j = 0; j < 49 - i; j++)
                {
                    float fzj = 0;
                    for (int k = 0; k < 10; k++)
                    {
                        if (fzeros[k, j] > fzeros[k, j + 1])
                        {
                            fzj = fzeros[k, j + 1];
                            fzeros[k, j] = fzeros[k, j + 1];
                            fzeros[k, j + 1] = fzj;
                        }
                    }
                }

            }
            for (int i = 0; i < 10; i++)
            {
                float fzh = 0;
                for (int j = 10; j < 40; j++)
                {
                    fzh += fzeros[i, j];
                }
                fAIDataZero[i] = fzh / 30;
            }



            //处理检测到信号板AI信号为0的情况

            if (fAIDataZero[0] < 100 && fAIDataZero[1] < 100 && fAIDataZero[2] < 100/* && fAIDataZero[3] < 100*/ )
            {
                //关闭串口，重新打开串口
                iniclass iniobj = new iniclass();
                string path = "";
                path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
                string path1 = string.Format(@"{0}", path);
                iniobj.Ini(path1);

                string sSetCom = iniobj.ReadValue("串口设置", "信号处理模块");
                string version = iniobj.ReadValue("通道设置", "信号板新协议版本");
                if (sSetCom != "")
                {
                    dacxh[0].close();//关闭 再打开
                    opencomm(sSetCom, 1, version);

                }
                if (icount > 3)
                    return;
                Thread.Sleep(1000);
                tiaoling(++icount);
            }
            return;

            //

        }

        // 最终采样值
        public float getcyz(string sName, float fSourceData)//通过力获取涡流
        {
            if (!getxh(sName))
            {
                return 0;
            }
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\标定数据.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);

            string sSet;
            sSet = objini.ReadValue("标定", sName);
            if (sSet.Length <= 0)
            {
                return 0;
            }
            string[] sbdsj = sSet.Split(';');
            string[] sbdfr = sbdsj[0].Split(',');
            string[] sbdfs = sbdsj[1].Split(',');

            float[] m_DataCYZ;
            float[] m_DataJSZ;

            m_DataCYZ = new float[sbdfr.Length - 1];
            m_DataJSZ = new float[sbdfr.Length - 1];
            for (int kk = 0; kk < sbdfr.Length - 1; kk++)
            {
                float.TryParse(sbdfr[kk], out m_DataCYZ[kk]);
                float.TryParse(sbdfs[kk], out m_DataJSZ[kk]);

            }
            int nSize = m_DataCYZ.Length;
            if (nSize < 2)
                return 0;
            int i = 0;
            for (i = 0; i < nSize; i++)
            {
                if (fSourceData < m_DataJSZ[i])
                    break;
            }

            float fValue;
            i = System.Math.Max(1, i);
            i = System.Math.Min(nSize - 1, i);

            fValue = m_DataCYZ[i - 1] + (fSourceData - m_DataJSZ[i - 1])
                * (m_DataCYZ[i] - m_DataCYZ[i - 1])
                / (m_DataJSZ[i] - m_DataJSZ[i - 1]);
            fValue = (float)Math.Round(fValue, 2);

            return fValue;
        }

        public float getwoliu(string sName, float fSourceData)//通过涡流码值获取力
        {
            if (!getxh(sName))
            {
                return 0;
            }
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\标定数据.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);

            string sSet;
            sSet = objini.ReadValue("标定", sName);
            if (sSet.Length <= 0)
            {
                return 0;
            }
            string[] sbdsj = sSet.Split(';');
            string[] sbdfr = sbdsj[0].Split(',');
            string[] sbdfs = sbdsj[1].Split(',');

            float[] m_DataCYZ;
            float[] m_DataJSZ;

            m_DataCYZ = new float[sbdfr.Length - 1];
            m_DataJSZ = new float[sbdfr.Length - 1];
            for (int kk = 0; kk < sbdfr.Length - 1; kk++)
            {
                float.TryParse(sbdfr[kk], out m_DataCYZ[kk]);
                float.TryParse(sbdfs[kk], out m_DataJSZ[kk]);

            }
            int nSize = m_DataCYZ.Length;
            if (nSize < 2)
                return 0;
            int i = 0;
            for (i = 0; i < nSize; i++)
            {
                if (fSourceData < m_DataJSZ[i])
                    break;
            }

            float fValue;
            i = System.Math.Max(1, i);
            i = System.Math.Min(nSize - 1, i);

            //fValue = m_DataCYZ[i - 1] + (fSourceData - m_DataJSZ[i - 1])
            //    * (m_DataCYZ[i] - m_DataCYZ[i - 1])
            //    / (m_DataJSZ[i] - m_DataJSZ[i - 1]);

            fValue = m_DataJSZ[i - 1] + (fSourceData - m_DataCYZ[i - 1]) * (m_DataJSZ[i] - m_DataJSZ[i - 1]) / (m_DataCYZ[i] - m_DataCYZ[i - 1]);
            fValue = (float)Math.Round(fValue, 2);

            return fValue;
        }
        // 传送信号名称获取最终计算值
        public float getjsz(string sName, float fSourceData)//获取计算值
        {

            //return 25;
            //Debug.WriteLine(string.Format("获取最终计算值时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "1"));
            if (!getxh(sName))
            {
                return 0;
            }
            //Debug.WriteLine(string.Format("获取最终计算值时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "2"));
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\标定数据.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);

            string sSet;
            sSet = objini.ReadValue("标定", sName);
            if (sSet.Length <= 0)
            {
                return 0;
            }
            //Debug.WriteLine(string.Format("获取最终计算值时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "3"));
            string[] sbdsj = sSet.Split(';');
            string[] sbdfr = sbdsj[0].Split(',');
            string[] sbdfs = sbdsj[1].Split(',');

            float[] m_DataCYZ;
            float[] m_DataJSZ;

            m_DataCYZ = new float[sbdfr.Length - 1];
            m_DataJSZ = new float[sbdfr.Length - 1];
            for (int kk = 0; kk < sbdfr.Length - 1; kk++)
            {
                float.TryParse(sbdfr[kk], out m_DataCYZ[kk]);
                float.TryParse(sbdfs[kk], out m_DataJSZ[kk]);

            }
            int nSize = m_DataCYZ.Length;
            if (nSize < 2)
                return 0;
            int i = 0;
            for (i = 0; i < nSize; i++)
            {
                if (fSourceData < m_DataCYZ[i])
                    break;
            }

            float fValue;
            i = System.Math.Max(1, i);
            i = System.Math.Min(nSize - 1, i);

            fValue = m_DataJSZ[i - 1] + (fSourceData - m_DataCYZ[i - 1])
                * (m_DataJSZ[i] - m_DataJSZ[i - 1])
                / (m_DataCYZ[i] - m_DataCYZ[i - 1]);
            fValue = (float)Math.Round(fValue, 2);
            //Debug.WriteLine(string.Format("获取最终计算值时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "4"));
            //if ("测功速度" == sName)
            //    return 75;
            //if (fValue < 0)
            //    fValue = 0;
            return fValue;
        }

        public bool getxh(string sName)
        {
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "1"));
            if (sName == "涡流输出")
                return true;
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "2"));
            iniclass iniobj = new iniclass();
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
            string path1 = string.Format(@"{0}", path);
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "3"));
            iniobj.Ini(path1);
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "4"));
            for (int i = 0; i < 10; i++)
            {
                string sgetname = iniobj.ReadValue("通道设置", string.Format(@"模拟信号{0}", i + 1));
                if (sgetname == sName)
                {
                    return true;
                }
                if (sName.Contains("制动力"))
                {
                    return true;
                }
            }
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "5"));
            for (int i = 0; i < 4; i++)
            {
                string sgetname = iniobj.ReadValue("通道设置", string.Format(@"速度{0}", i + 1));
                if (sgetname == sName)
                {
                    return true;
                }
            }
            //Debug.WriteLine(string.Format("getxh时间：{0}名字：{1}节点：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), sName, "6"));
            return false;
        }

        //---------------------------------------------------------------
        public void LiftJZ(bool uStates, short isheng, short ijian)
        {
            if (uStates)
            {
                //确保清零
                SetDOBit(isheng, 0);
                Thread.Sleep(300);
                SetDOBit(ijian, 0);
                //再发送指令
                SetDOBit(isheng, 1);

            }
            else
            {

                //确保清零
                SetDOBit(isheng, 0);
                Thread.Sleep(300);
                SetDOBit(ijian, 0);
                //再发送指令
                SetDOBit(ijian, 1);
                //防止继电器一直开放
                //    SetDOBit(ijian, 0);           
            }
        }//加载控制
        public void StopDJ(short danjiz, short dianjiy)
        {
            SetDOBit(danjiz, 0);
            SetDOBit(dianjiy, 0);
        }

        public void LiftTwoSL(short ijin)//, short isong)//两路控制举升
        {
            for (int i = 0; i < 3; i++)
            {
                //SetDOBit(ijin, (short)(uStates ? 1 : 0));
                SetDOBit(ijin, 1);
                Thread.Sleep(10);
            }
            Thread.Sleep(50);
            for (int k = 0; k < 3; k++)
            {
                SetDOBit(ijin, 0);
                Thread.Sleep(10);
            }
        }

        public void Lift(bool uStates)
        {
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);
            string sjjlukz;//举升是否两路控制
            sjjlukz = objini.ReadValue("通道设置", "举升两路控制");
            short ijushengS = 0, ijushengJ = 0;
            for (int i = 0; i < 8; i++)
            {
                string sSetTongDao = objini.ReadValue("通道设置", string.Format("控制{0}", i + 1));
                if (sSetTongDao != "")
                {

                    if (sSetTongDao.Contains("测功举升升"))
                    {
                        ijushengS = (short)i;
                    }
                    else if (sSetTongDao.Contains("测功举升降"))
                    {
                        ijushengJ = (short)i;
                    }
                }
            }
            if (sjjlukz.Contains("是"))
            {
                if (uStates)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(ijushengS, 1);
                        Thread.Sleep(200);

                    }
                    Thread.Sleep(500);
                    for (int k = 0; k < 3; k++)
                    {
                        SetDOBit(ijushengS, 0);
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(ijushengJ, 1);
                        Thread.Sleep(200);
                    }
                    Thread.Sleep(500);
                    for (int k = 0; k < 2; k++)
                    {
                        SetDOBit(ijushengJ, 0);
                        Thread.Sleep(200);
                    }
                }
            }
            else
            {
                if (uStates)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(ijushengJ, 1);
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(ijushengJ, 0);
                        Thread.Sleep(200);
                    }
                }

            }

        }
        public void LiftOne(bool uStates, short isheng)//一路控制举升
        {

            if (uStates)
            {
                SetDOBit(isheng, 1);

            }
            else
            {
                SetDOBit(isheng, 0);
            }


        }
        public void LiftTwo(bool uStates, short isheng, short ijian)//两路控制举升
        {
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);
            string sjjlukz;//举升是否两路控制
            string sliftcontrary;//举升取反
            sjjlukz = objini.ReadValue("通道设置", "举升两路控制");
            sliftcontrary = objini.ReadValue("通道设置", "举升取反");

            if (sliftcontrary.Contains("是"))
            {
                uStates = !uStates;
            }

            if (sjjlukz.Contains("是"))
            {
                if (uStates)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(isheng, 1);
                        Thread.Sleep(200);

                    }
                    Thread.Sleep(500);
                    for (int k = 0; k < 3; k++)
                    {
                        SetDOBit(isheng, 0);
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(ijian, 1);
                        Thread.Sleep(200);
                    }
                    Thread.Sleep(500);
                    for (int k = 0; k < 2; k++)
                    {
                        SetDOBit(ijian, 0);
                        Thread.Sleep(200);
                    }
                }
            }
            else
            {
                if (uStates)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(isheng, 1);
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    for (int i = 0; i < 2; i++)
                    {
                        SetDOBit(isheng, 0);
                        Thread.Sleep(200);
                    }
                }
            
            }

        }

        public void setsjjl(bool bdqxhb, string stxtmc)
        {
            //dacxh[0].fAIDataZeroduoshao[0] = fAIDataZero[0];
            dacxh[0].sxhbmc = string.Format("{0}1号板", stxtmc);
            dacxh[1].sxhbmc = string.Format("{0}2号板", stxtmc);
            if (bdqxhb)
            {
                {
                    StringBuilder strBuider1 = new StringBuilder();
                    for (int i = 0; i < 5; i++)
                    {
                        strBuider1.Append(string.Format("零位{0}：{1}\r\n", i + 1, fAIDataZero[i]));

                    }
                    dacxh[0].Write(string.Format("./{0}信号.txt", dacxh[0].sxhbmc), strBuider1.ToString());
                }
                {
                    StringBuilder strBuider1 = new StringBuilder();
                    for (int i = 0; i < 5; i++)
                    {
                        strBuider1.Append(string.Format("零位{0}：{1}\r\n", i + 1, fAIDataZero[i + 5]));

                    }
                    dacxh[1].Write(string.Format("./{0}信号.txt", dacxh[1].sxhbmc), strBuider1.ToString());
                }
            }
            dacxh[0].bdqxhb = bdqxhb;
            dacxh[1].bdqxhb = bdqxhb;
        }
        //-----------------------------------------------------------------
    }
}
